import 'package:cave_flutter/config/whl_base_controller.dart';
import 'package:cave_flutter/model/base_model.dart';
import 'package:cave_flutter/model/whl_user_info_model.dart';
import 'package:cave_flutter/network/whl_api.dart';
import 'package:cave_flutter/pages/whl_main/whl_main_logic.dart';
import 'package:cave_flutter/pages/whl_mine/edit_userinfo/edit_userinfo_view.dart';
import 'package:cave_flutter/utils/whl_db_utils.dart';
import 'package:cave_flutter/utils/whl_toast_utils.dart';
import 'package:cave_flutter/utils/whl_user_utils.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

import '../../db_manager/bean/whl_product_bean.dart';
import '../../routes/whl_app_pages.dart';
import '../../utils/whl_current_limiting_util.dart';
import 'cave_welfare/cave_welfare_view.dart';
import 'task/task_view.dart';

enum TabType {
  wallet,
  vipCenter,
  safeCenter,
  mall,
}

enum MineType {
  myProduct,
  task,
  blockList,
  setting,
  medalWall,
  cavePublic,
  sponsorCave,
}

class WhlMineLogic extends WhlBaseController {
  WhlUserInfoModel userInfoModel = WhlUserInfoModel();
  int selectedIndex = 0;
  List<WhlProductBean> myProductList = [];
  PageController pageController = PageController();
  List<WhlUserInfoModel> blockUserList = [];
  bool isAutoTranslate = true;
  List<BaseModel> tabList = [
    BaseModel(
        title: '钱包', icon: 'icon_mine_wallet.png', tabType: TabType.wallet),
    BaseModel(
        title: '会员中心',
        icon: 'icon_mine_vip_center.png',
        tabType: TabType.vipCenter),
    BaseModel(
        title: '认证中心', icon: 'icon_mine_safe.png', tabType: TabType.safeCenter),
    BaseModel(title: '商城', icon: 'icon_mine_mall.png', tabType: TabType.mall),
  ];

  List<BaseModel> mineList = [
    BaseModel(
        title: '个人主页',
        icon: 'icon_mine_my_product.png',
        mineType: MineType.myProduct),
    BaseModel(
        title: '每日任务',
        icon: 'icon_mine_my_product.png',
        mineType: MineType.task),
    BaseModel(
        title: '灵魂契约',
        icon: 'icon_mine_block_list.png',
        mineType: MineType.blockList),
    BaseModel(
        title: '人格测试',
        icon: 'icon_mine_setting.png',
        mineType: MineType.setting),
    // BaseModel(
    //     title: '勋章墙',
    //     icon: 'icon_mine_setting.png',
    //     mineType: MineType.medalWall),
    BaseModel(
        title: 'Cave公益',
        icon: 'icon_mine_setting.png',
        mineType: MineType.cavePublic),
    BaseModel(
        title: '赞助Cave',
        icon: 'icon_mine_setting.png',
        mineType: MineType.sponsorCave),
  ];

  EasyRefreshController easyRefreshController = EasyRefreshController(
      controlFinishLoad: true, controlFinishRefresh: true);

  @override
  void onInit() {
    super.onInit();
    onGetUserInfo();
    // onGetMyProductList();
    isAutoTranslate = WhlUserUtils.getIsAutoTranslate();
  }

  onGetMyProductList() async {
    // myProductList = await WhlDBUtils().productDao.findProductByUserId(WhlUserUtils.getId()) ?? [];
    // update();
  }

  onGetUserInfo() async {
    ResponseData responseData = await WhlApi.myHome.get({});
    if (responseData.isSuccess()) {
      userInfoModel = WhlUserInfoModel.fromJson(responseData.data);
      print("【cave】${userInfoModel.toJson()}");

      update();
      /*
      WhlUserInfoModel oldUserModel = WhlUserUtils.getUserInfo();
      oldUserModel.isTask = userInfoModel.isTask;
      oldUserModel.memberGrade = userInfoModel.memberGrade;
      oldUserModel.userId = userInfoModel.userId;
      */
      WhlUserUtils.saveUserInfo(userInfoModel);
    }
    easyRefreshController.finishRefresh();
  }

  onGetBlockList() async {
    // ResponseData responseData = await WhlApi.blockList.post({});
    // if (responseData.isSuccess()) {
    //   blockUserList = (responseData.data as List).map((e) => WhlUserInfoModel.fromJson(e)).toList();
    //   update();
    // }
  }

  doClickCopy() {
    Clipboard.setData(ClipboardData(text: userInfoModel.id ?? ''));
    MyToast.show("Copy Success");
  }

  doClickLike(WhlProductBean model) {
    model.isLike = !model.isLike!;
    model.likeNum = (model.likeNum ?? 0) + (model.isLike! ? 1 : -1);
    update();
    WhlDBUtils().productDao.updateProduct(model);
  }

  onPageChanged(index, {bool isClick = false}) {
    selectedIndex = index;
    if (isClick) {
      pageController.jumpToPage(selectedIndex);
    }
    update();
    if (selectedIndex == 0) {
      onGetMyProductList();
    } else if (selectedIndex == 1) {
      WhlCurrentLimitingUtil.debounce(() {
        onGetBlockList();
      });
    }
  }

  doClickUnblock(WhlUserInfoModel model) async {
    Map<String, dynamic> params = {
      'blockUserId': model.id,
    };
    // ResponseData responseData = await WhlApi.removeBlock.post(params);
    // if (responseData.isSuccess()) {
    //   blockUserList.remove(model);
    //   update();
    //   List<String> blockList = WhlUserUtils.getBlockList();
    //   if (blockList.contains(model.id)) {
    //     blockList.remove(model.id);
    //     WhlUserUtils.setBlockList(blockList);
    //   }
    // }
  }

  doClickUserInfo() {
    Get.toNamed(Routes.settingUserInfo)?.then((value) {
      // if (value != null && value) {
      onGetUserInfo();
      // }
    });
  }

  doClickListViewItem(BaseModel model) {
    if (model.mineType == MineType.myProduct) {
      Get.toNamed(Routes.userInfo);
    } else if (model.mineType == MineType.cavePublic) {
      Get.to(() => Cave_welfarePage());
    } else if (model.mineType == MineType.task) {
      Get.to(() => TaskPage());
    } else if (model.mineType == MineType.medalWall) {
      Get.toNamed(Routes.medalWall);
    } else if (model.mineType == MineType.setting) {
      Get.toNamed(Routes.personalityTest);
    } else {
      MyToast.show('该功能暂未开放');
    }
  }

  doClickAutoTranslateSwitch(bool isTranslate) {
    WhlUserUtils.setIsAutoTranslate(isTranslate);
  }

  doClickDeleteProduct(WhlProductBean model) async {
    await WhlDBUtils.instance.productDao.deleteProduct(model);
    onGetMyProductList();
  }

  onLogout() async {
    // ResponseData responseData = await WhlApi.logout.post({});
    // if (responseData.isSuccess()) {
    //   WhlNetWorkUtils.setAccessToken('');
    //   ChatManager.getInstance().logoutIM();
    //   // WhlRCIMUtils.engine.disconnect(false);
    //   Get.offAllNamed(Routes.login);
    // }
  }

  onDeleteAccount() async {
    // ResponseData responseData = await WhlApi.deleteAccount.post({});
    // if (responseData.isSuccess()) {
    //   WhlNetWorkUtils.setAccessToken('');
    //   // WhlRCIMUtils.engine.disconnect(false);
    //   ChatManager.getInstance().logoutIM();
    //   Get.offAllNamed(Routes.login);
    // }
  }

  doClickCustomService(BuildContext context) async {
    doClickService();
    // Future.delayed(Duration(milliseconds: 200)).then((value) {
    //   showDebugBtn(context);
    // });
  }

  doClickSetting() async {
    WhlMainLogic logic = Get.find();
    logic.openDrawer();
  }

  toNextTabPage(TabType? type) {
    if (type == TabType.wallet) {
      Get.toNamed(Routes.walletPage);
    } else if (type == TabType.vipCenter) {
      Get.toNamed(Routes.mineVipPage);
    } else if (type == TabType.safeCenter) {
    } else if (type == TabType.mall) {
    } else {
      MyToast.show('该功能暂未开放');
    }
  }

  void toEditUserInfoPage() {
    Get.to(() => Edit_userinfoPage());
  }

  void refreshAction() {
    onGetUserInfo();
  }
}
